1. Selectors分別取到什麼?

getElementBy- : 較早期語法
document.getElementsByClassName('xxx') 取得所有DOM (HTMLCollection)
document.querySelector('xxx') 取得所有節點 (NodeList)
document.querySelectorAll('xxx') 取得所有節點

getElementById() is only available as a method of the global document object, and not available as a method on all element objects in the DOM. Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function.

Devtool看HTMLCollection和NodeList

2. Q: HTMLCollection 和 NodeList 使用上差異? 補

HTMLCollection

DOM 節點有4種: element、attribute、text、comment
HTMLCollection會篩選出 element類型的節點(HTML元素形成的節點)。

<ul>
    <li> a </li>
    <li> b </li>
    <li> c </li>
</ul>
錯誤寫法
document.querySelectorAll('ul').children
//undefined

正確寫法
document.querySelector('ul').children
// HTMLCollection(3)[li, li, li]

正確寫法
document.querySelectorAll("ul li")
//NodeList(3) [li, li, li]

NodeList 只能唯讀操作,不能新增刪除元素

let item = document.querySelectorAll("li")

  • 查看長度 item.length //3
  • 遍歷內容 item.forEach(i => console.log(i))
  • 使用 index 來存取特定項目 item[2] // <li>c</li>
    NodeList和DOM是連動的,在DevTool中需透過DOM操作修改網頁內容。

3. 類陣列使用情境

情境: 當有相同名稱 class="box" 時,一同選取3個元素做監聽或迭代,2種選取方法都是得到 類陣列的集合 => 無法使用陣列的方法

<div class="box" id="0"></div>
<div class="box" id="1"></div>
<div class="box" id="2"></div>

4. Q:取得 類陣列 後如何使用陣列的方法?

A:轉換為陣列 Array.from(類陣列)

Array.from((必)target: 類陣列or可迭代物件, (選) mapFn, (選) thisValue)

不改變原本的target
回傳: 陣列

(必)target: 要轉成貞烈的對象:類陣列or可迭代物件 |default: 無

  • 類陣列:

    • selectors選取後的集合(HTMLCollection / NodeList)
    • 物件具有 length 屬性以及索引(indexed)的元素
  • 可迭代物件: 補

(選) mapFn: function |default: undefined

  • map方法遍歷陣列元素

(選) thisValue object |default: undefined

  • 指定mapFn方法的this對象
function plusValue(numbers) {
  return Array.from(arguments, (number)=> number + 10);
}
console.log(plusValue(1, 2, 3))
// [object Array] (3)
[11,12,13]

CSS Selectors -選擇器可以定義某組 CSS 樣式要套用到哪些元素上。

getElementById()
getElementsByClassName()
getElementsByName()
getElementsByTagName()
getElementsByTagNameNS()
querySelector()
querySelectorAll()


#selectors #array-like #htmlcollection #nodelist #Array.from #getelementsbyclassname #querySelectorAll







Related Posts

Day 6 - While Loop & Karel

Day 6 - While Loop & Karel

欄column (下)筆記Day -3

欄column (下)筆記Day -3

[Vue3] 元件溝通術 props、emits、slot 、mitt怎麼用

[Vue3] 元件溝通術 props、emits、slot 、mitt怎麼用


Comments